using AutoMapper;
using ExamServer.Entities;
using ExamServer.Models;
using ExamServer.Service;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ExamServer.Controllers
{
  [ApiController]
  [Route("[controller]")]
  public class QuestionTypeController : ControllerBase
  {
    public QuestionTypeController(IRepositoryWrapper wrapper, IMapper mapper)
    {
      Wrapper = wrapper;
      Mapper = mapper;
    }

    public IRepositoryWrapper Wrapper { get; }
    public IMapper Mapper { get; }

    #region 查询
    [HttpGet]
    public async Task<ActionResult<IEnumerable<QuestionTypeModel>>> Get()
    {
      var list = Mapper.Map<IEnumerable<QuestionTypeModel>>(await Wrapper.QuestionTypes.GetAllAsync());
      return Ok(list);
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<QuestionTypeModel>> GetModel(int id)
    {
      var entity = await Wrapper.QuestionTypes.GetByIdAsync(id);
      if (entity == null)
      {
        return NotFound();
      }
      var model = Mapper.Map<QuestionTypeModel>(entity);
      return Ok(model);
    }
    #endregion

    #region 插入
    [HttpPost]
    public async Task<IActionResult> Insert([FromForm]QuestionTypeModel model)
    {
      var entity = new QuestionType();
      entity.TypeName = model.TypeName;
      entity.Remark = model.Remark;
      entity.TypeState = (StateEnum)Enum.Parse(typeof(StateEnum), model.StateDisplay);
      Wrapper.QuestionTypes.Creatre(entity);
      var bl = await Wrapper.QuestionTypes.SaveAsync();
      return new JsonResult(new {
        status=bl,
        message=bl?"添加成功":"添加失败"
      });
    }
    #endregion

    #region 修改
    [HttpPut]
    public async Task<IActionResult> Update([FromForm]QuestionTypeModel model)
    {
      var entity = new QuestionType();
      entity.Id = model.Id;
      entity.Remark = model.Remark;
      entity.TypeName = model.TypeName;
      entity.TypeState = (StateEnum)Enum.Parse(typeof(StateEnum), model.StateDisplay);
      Wrapper.QuestionTypes.Update(entity);
      var bl = await Wrapper.QuestionTypes.SaveAsync();
     return new JsonResult(new{
       status=bl,
       message=bl?"修改成功":"修改失败"
     });
    }
    #endregion

    #region 删除 伪删除
    [HttpDelete]
    public async Task<IActionResult> Delete([FromForm]int id)
    {
      var entity = await Wrapper.QuestionTypes.GetByIdAsync(id);
      if (entity == null)
      {
        return BadRequest();
      }
      entity.TypeState = entity.TypeState == StateEnum.不可用 ? StateEnum.可用 : StateEnum.不可用;//可用不可用来回切换
      Wrapper.QuestionTypes.Update(entity);
      bool bl = await Wrapper.QuestionTypes.SaveAsync();
      return new JsonResult(new
      {
        status = bl,
        message = bl ? "操作成功" : "操作失败"
      });

    }
    #endregion
  }
}